package org.university.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.university.entity.ClassroomAssignment;
import org.university.repository.ClassroomAssignmentRepository;
import org.university.service.ClassroomAssignmentService;

@Service
public class ClassroomAssignmentServiceImpl extends GenericServiceImpl<ClassroomAssignment, Integer> implements ClassroomAssignmentService {

    private static final Logger logger = LoggerFactory.getLogger(ClassroomAssignmentServiceImpl.class);
    private final ClassroomAssignmentRepository classroomAssignmentRepository;

    public ClassroomAssignmentServiceImpl(ClassroomAssignmentRepository repository, ClassroomAssignmentRepository classroomAssignmentRepository) {
        super(repository);
        this.classroomAssignmentRepository = classroomAssignmentRepository;
    }

    // FIXME 新建逻辑可能有问题，应该是检测时间是否空余，而不是单纯的检测id
    @Override
    public ClassroomAssignment save(ClassroomAssignment classroomAssignment) {
        Integer id = classroomAssignment.getAssignmentId();
        logger.info("保存【教室分配】ID: {}", id);
        if (id != null && classroomAssignmentRepository.existsById(id)) {
            throw new IllegalArgumentException("【教室分配】ID已存在: " + id);
        }
        return classroomAssignmentRepository.save(classroomAssignment);
    }

    @Override
    public Page<ClassroomAssignment> findAll(Pageable pageable) {
        logger.info("查询所有【教室分配】: 分页信息={}", pageable);
        return classroomAssignmentRepository.findByDeletedFalse(pageable);
    }

    @Override
    public Page<ClassroomAssignment> findAll() {
        logger.info("查询所有【教室分配】（无分页）");
        return classroomAssignmentRepository.findByDeletedFalse(Pageable.unpaged());
    }

    @Override
    public void deleteById(Integer id) {
        logger.info("删除【教室分配】ID: {}", id);
        classroomAssignmentRepository.findById(id).ifPresent(classroomAssignment -> {
            classroomAssignment.setDeleted(1);
            classroomAssignmentRepository.save(classroomAssignment);
        });
    }
}